using System.Threading;
using ebcpatterns.concurrent;
using NUnit.Framework;

namespace ebcpatterns.tests.concurrent
{
    [TestFixture]
    public class ThrottleTests
    {
        private EventWaitHandle waitHandle;

        [SetUp]
        public void Setup() {
            waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
        }

        [Test]
        public void Throttle_delays_event_for_5_seconds() {
            var sut = new Throttle<string>();
            var result = "";
            sut.Result += x => {
                result = x;
                waitHandle.Set();
            };

            sut.Process("x");
            sut.Process("y");
            sut.Process("z");

            Assert.That(waitHandle.WaitOne(6000), Is.True);
            Assert.That(result, Is.EqualTo("z"));
        }

        [Test]
        public void Throttle_delays_event_for_given_milliseconds() {
            var sut = new Throttle<string>(200);
            var result = "";
            sut.Result += x => {
                result = x;
                waitHandle.Set();
            };

            sut.Process("x");
            sut.Process("y");
            sut.Process("z");

            Assert.That(waitHandle.WaitOne(600), Is.True);
            Assert.That(result, Is.EqualTo("z"));
        }
    }
}